<template>
  <div class="wrap">
    <input type="file" @change="parseDocx" accept=".docx" />
    <div>{{ parsedText }}</div>
  </div>
</template>
<script>
import { Editor } from "@tiptap/vue-2";
import StarterKit from "@tiptap/starter-kit";
// import { Node } from "@tiptap/core";
import JSZip from "jszip";
import { DOMParser } from "xmldom";

export default {
  components: {},
  data() {
    return {
      editor: null,
      parsedText: "",
    };
  },
  mounted() {
    // const CustomDiv = Node.create({
    //   name: "customDiv",
    //   group: "block",
    //   content: "inline*",
    //   attributes: "12ca",
    //   parseHTML() {
    //     return [{ tag: "div" }, { tag: "span" }];
    //   },
    //   renderHTML({ HTMLAttributes }) {
    //     console.log("HTMLAttributes===", HTMLAttributes);
    //     return ["div", HTMLAttributes, 0];
    //   },
    // });

    this.editor = new Editor({
      element: this.$refs.editorElement,
      extensions: [StarterKit],
      content: `<div class='customDiv' >Start typing...</div><p>我是P</p><span>我是sPan</span>`,
      // onUpdate: () => {
      //   // 内容变化时触发
      //   this.$emit("update", this.editor.getHTML());
      // },
    });
  },
  methods: {
    async parseDocx(event) {
      const file = event.target.files[0];
      if (!file) return;

      try {
        // 1. 读取并解压.docx文件
        const zip = new JSZip();
        const zipData = await zip.loadAsync(file);

        // 2. 提取核心XML内容
        const documentXML = await zipData
          .file("word/document.xml")
          .async("string");
        console.log("documentXML---", documentXML);

        // 3. 解析XML并提取文本
        const doc = new DOMParser().parseFromString(documentXML, "text/xml");
        console.log("doc---", doc);

        // const tiptapContent = await this.parseWordDocument(doc, zipData);
        // this.editor.commands.setContent(tiptapContent);
        const textNodes = doc.getElementsByTagName("w:t");
        console.log("textNodes---", textNodes);

        // 遍历所有文本节点
        let content = "";
        for (let i = 0; i < textNodes.length; i++) {
          content += textNodes[i].textContent + " ";
        }
        console.log("content---", content);

        this.parsedText = content.replace(/\s+/g, " ").trim();
      } catch (err) {
        console.error("解析失败:", err);
      }
    },
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy();
    }
  },
};
</script>
<style lang="scss" scoped>
.mainContent {
  display: flex;
  .toc-sidebar {
    width: 20%;
    .toc-item {
      white-space: nowrap;
      text-align: left;
      text-overflow: ellipsis;
      overflow: hidden;
      cursor: pointer;
      margin: 4px 0;
    }
  }
  .editorElement {
    flex: 1;
  }
}
</style>